<?php
    class user_Ajax extends Ajax
    {
        public function checkUserID()
        {
            $sUserID = $_POST['username'];
            $oDatabase = new database();
            $aListProduct = $oDatabase->getListObject("select * from user where user_id='".$sUserID."'" );
            if(count($aListProduct))
            {
                echo 'Fail';
            } 
            else
            {
                echo 'true' ;
            }
        }
        public function addUser()
        {
            $_SESSION['register'] = 'true';
            $oDatabase = new database();
            $uri = URL::getLink("profile/id/".$_POST['username']);
            $aData = array(
                'user_id' => $_POST['username'],
				// base64_decode
                'pass' => base64_encode($_POST['password']),    
                'fullname' => $_POST['fullname'],
                'address' => $_POST['address'],
                'uri' => $uri,
                'online' =>0,
                'active' =>0,
                'avatar'=> 'defaultavata.png'
            );
            $result = $oDatabase->add('user',$aData); 
            if($result)
            {
                /** If add susscessfuly, create a new resources rdf and load data into ARC2Store*/
                $this->createResources();
                echo "Success";
            }
        }
        /**
        *   Function create file rdf and load into ARC2Store
        */
        public function createResources()
        {
            // Add namespace for rdf file
            $ns = array(
                'rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
                'foaf' => 'http://xmlns.com/foaf/0.1/',
                'bus' => URL::getLink('id/bussiness#'),
            );
            $conf = array('ns' => $ns);
            $ser = ARC2::getRDFXMLSerializer($conf);
            $uri = URL::getLink('profile/id/'.$_POST['username']);
            $index = array(
                $uri => array(
                    "rdf:type" => array( 
                        array( "value" => "http://xmlns.com/foaf/0.1/Person", 
                            "type" => "uri" ) 
                    ) ,
                    "foaf:familyName" => array(
                        array( "value" => $_POST['fullname'], 
                            "type" => "literal")
                    ),
                    "foaf:givenName" => array(
                        array( "value" => $_POST['username'], 
                            "type" => "literal")
                    ),
                    "bus:location" => array(
                        array( "value" => $_POST['address'], 
                            "type" => "literal")
                    ),
                    "foaf:mbox" => array(
                        array( "value" => $_POST['email'], 
                            "type" => "literal")
                    ),
                    "bus:hasSetting" => array(
                        array( "value" => URL::getLink('id/'.$_POST['username'].'_setting'),
                            "type" => "literal",
                        )
                    ),
                ) 
            );

            $oDatabase = new database();
            $oDatabase->createResources($ns, $index,$_POST['username'],'profile');
            // Tao user_hotproduct
            $uri = URL::getLink('id/'.$_POST['username'].'_hotProduct');
            $index = array(
                $uri => array(
                    "rdf:type" => array( 
                        array( "value" => URL::getLink("id/bussiness#hotProduct"), 
                            "type" => "uri" ) 
                    ) ,
                ) 
            );   
            $oDatabase->createResources($ns, $index,$_POST['username'].'_hotProduct'); 
            // Tao user_setting
            $uri = URL::getLink('id/'.$_POST['username'].'_setting');
            $index = array(
                $uri => array(
                    "rdf:type" => array( 
                        array( "value" => URL::getLink("id/bussiness#setting"), 
                            "type" => "uri" ) 
                    ) ,

                ) 
            );   
            $oDatabase->createResources($ns, $index,$_POST['username'].'_setting'); 
        }
        public function checkLogin()
        {
            if(isset($_POST['username']) && isset($_POST['password']))
            {
                $oDatabase = new database();
                $sQuery= "
                SELECT * FROM user 
                WHERE user_id='".$_POST['username']."' 
                AND pass='".base64_encode($_POST['password'])."'" ;
                $oUser = $oDatabase->getObject($sQuery);
                if($oUser)
                {
                    $active = 0;
                    core::checkSession();
                    if(isset($_SESSION['register']))
                        $active = 1;
                    $active = 0;
                    $status = $_POST['status'];
                    $aCondition = array(
                        'user_id = "'.$_POST['username'] => '"',

                    );
                    $aData = array(
                        'online' => (int)$status , 
                        'active' =>$active 
                    );
                    $result = $oDatabase->update('user',$aData, $aCondition);
                    $_SESSION['username'] = $_POST['username'];
                    $_SESSION['user_uri'] = $oUser->uri;
                    $uri = $oUser->uri;
                    $graph = new Graphite();
                    $graph->ns('bus',URL::getLink('id/bussiness#'));
                    $graph->load($uri);
                    
                    $image = $graph->resource($uri)->get('bus:image');
                    if($graph->resource($uri)->has('bus:image'))
                    {
                        $_SESSION['avatar'] = $image;
                    }
                    // Load setting
                    if($oUser->type == 'admin')
                    {
                        $uri = URL::getLink('id/setting');
                    }
                    else
                    {
                        $uri = URL::getLink('id/'.$_SESSION['username'].'_setting');
                    }

                    $graph = new Graphite();
                    $graph->ns('bus', URL::getLink('id/bussiness#'));
                    $graph->load($uri);
                    $_SESSION['defaultProductLayout'] = ($graph->resource($uri)->has('bus:defaultProductLayout') ? $graph->resource($uri)->get('bus:defaultProductLayout'): 'default');
                    $_SESSION['defaultProductHightLightLayout'] = ($graph->resource($uri)->has('bus:defaultProductHightLightLayout') ? $graph->resource($uri)->get('bus:defaultProductHightLightLayout'): 'default');

                    echo "welcome $_POST[username]";
                }
                else
                {
                    echo "FAIL";
                }
            }
        }
        public function checkUsername()
        {
            session_start();
            if(isset($_SESSION['username']))
            {

                echo "welcome ".$_SESSION['username'];
            }
            else
            {
                echo 'Fail';
            }
        }
        function updateAvatar()
        {
            core::checkSession();

            if(!isset($_POST['image']))
            {
                echo 'FALSE';
                return;
            }
            if(!database::isUser())
            {
                echo 'FALSE';
                return;
            }
            $_SESSION['avatar'] = $_POST['image'];
            $oDatabase = new database();
            // Update in rdf resources and ARC2 Store
            $oDatabase->setProperity($_SESSION['user_uri'],'bus:image',URL::getLink('upload/'.$_POST['image']));
            // Update in user table in mysql
            $aData = array(
                'avatar' => $_POST['image']
            );
            $aCondition = array(
                "user_id = '".$_SESSION['username']."'" => '',
            );
            $oDatabase->update('user', $aData, $aCondition);
        }
        public function closeBrowser()
        {
            core::checkSession();
            $oDatabase = new database();
            $aCondition = array(
                'user_id = "'.$_SESSION['username'] => '"',
            );
            $aData = array(
                'online' => 0    
            );
            $result = $oDatabase->update('user',$aData, $aCondition);
        }
        public function loadNofication()
        {
            core::checkSession();
            $oDatabase = new database();
            $data ='';
            $data = $data.'<div class ="nofication_title"><lable id="id_title_nofication">Thông Báo</lable></div>';
            if(isset($_SESSION['username']))
            {
                $query ='select *from nofication where user_to="'.$_SESSION['username'].'" and status = 1 ORDER BY nofication_id ASC';
                $aNofication = $oDatabase->getListObject($query);
                if(count($aNofication))
                {
                    foreach($aNofication as $user)
                    {
                        $snofication =$this->printNotification($user);
                        $data.=$snofication;
                    }
                    $status ='1';
                    $aCondition = array(
                        'user_to = "'.$_SESSION['username'] => '" and',
                        'status ='.$status =>''
                    );
                    $aData = array(
                        'status' => 0    
                    );
                    $result = $oDatabase->update('nofication',$aData, $aCondition);
                }
                else
                {
                    $query ='select *from nofication where user_to="'.$_SESSION['username'].'" ORDER BY nofication_id DESC LIMIT 5';
                    $aNofication = $oDatabase->getListObject($query);
                    if(count($aNofication))
                    {
                        foreach($aNofication as $user)
                        {
                            $snofication =$this->printNotification($user);
                            $data.=$snofication;
                        }
                    }
                    else
                    {
                        $data .='<div class="no_notification"><lable>Bạn không có thông báo mới .</lable></div>';
                    }
                    if(count($aNofication)==5)
                    {
                        $data .='<div class ="nofication_title_bottom"><lable id="id_title_nofication">Xem tất cả</lable></div>';
                    }
                }

            }
            echo $data;
        }
        public function printNotification($user)
        {
            $icon ='';
            $type = $user->type;
            if($type == 1)
            {
                $icon ='pro_noti.png';
            }
            else
            {
                if($type == 2)
                {
                    $icon ='ment.png';
                }
                else
                {
                    $icon ='like.png';
                }
            }
            $data = '';
            $data.=' <div class="li_comment_nofication">' ;
            $data.='<div style="margin-bottom: 10px;">';
            $data.='<div style="float: left; width: 10%; margin-left : 5px;">';
            $data.='<img style=" height: 50px; width: 50px;" src="'.URL::getLink('upload/'.$user->avata).'"></div>';
            $data.='<div style="float:left;padding-left: 20px; width: 80%;">';
            $data.='<div class="arer_comment" style ="line-height :0px;">';
            $data.='<label hidden="" class="id_comment_product">'.$user->product.'</label>';
            $data.='<label style="color: #DF1B23; font-weight: bold;">'.$user->user_send.' </label>';
            $data.='<label style="font: 200 13px/1.5 Georgia, Times New Roman, serif;">'.$user->content.' </label><br> ';
            $data.='<label style="font: 200 11px/1.5 Georgia, Times New Roman, serif; color: #3581e0;"><img style="" src="'.URL::getLink('image/'.$icon).'"> <label style="font-size: 12px; color: #A6A6A6; ">Lúc : '.date('H:i Y-m-d' ,$user->time).'</label></label>';
            $data.='</div></div>';
            $data.='</div><div class="add_reply" style="clear: both;"></div></div>';
            return $data;
        }
        public function updateNotification()
        {
            core::checkSession();
            $oDatabase = new database();
            $data ='';
            if(isset($_SESSION['username']))
            {
                $query ='select *from nofication where user_to="'.$_SESSION['username'].'" and status = 1 ORDER BY nofication_id ASC';
                $aNofication = $oDatabase->getListObject($query);
                if(count($aNofication))
                {
                    $data =count($aNofication);
                }
            }
            echo $data;
        }

        public function setUserDefaultLayout()
        {
            if(!database::isUser())
            {
                return;
            }
            core::checkSession();
            if(isset($_POST['value']))
            {
                $oDatabase = new database();
                $uri = (database::isAdmin() ? URL::getLink('id/setting') : URL::getLink('id/'.$_SESSION['username'].'_setting'));
                $oDatabase->setProperity($uri,'bus:defaultProductLayout',$_POST['value']);
                $_SESSION['defaultProductLayout'] = $_POST['value'];
            }
        }
    }
?>
